﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.Transaction;
using Icoders.MarketTracker.Core.Transaction;
using Icoders.MarketTracker.Core.Validation;
using Icoders.MarketTracker.Data.EF;
using Icoders.MarketTracker.Data.Utils;

namespace Icoders.MarketTracker.Data.Repository.Transcation
{
    public class PurchaseOrderRepository : RepositoryBase, IPurchaseOrderRepository
    {
        private AppDataContext _ctx;

        public PurchaseOrderRepository(AppDataContext ctx)
       {
           _ctx = ctx;
       }
        public ValidationResultInfo Validate(PurchaseOrder objToValidate)
        {
            ValidationResultInfo vri = objToValidate.BasicValidation();
            //bool hasDuplicateName = GetAll().Where(v => v.Id != objToValidate.Id)
            //    .Any(p => p.PurchaseOrderRef == objToValidate.PurchaseOrderRef);
            //if (hasDuplicateName)
            //    vri.Results.Add(new ValidationResult("Duplicate Name Found"));
            return vri;
        }

        public Guid Save(PurchaseOrder entity)
        {
            
            DateTime date = TimeUtil.GetDateTime();
            ValidationResultInfo vri = Validate(entity);
            bool isSale = false;
            if (!vri.IsValid)
            {
                throw new DomainValidationException(vri, "Product Details provided not valid");
            }

            TblPurchase tbl = _ctx.TblPurchase.FirstOrDefault(s => s.Id == entity.Id);
           
            if (tbl == null)
            {
                tbl = new TblPurchase();
                tbl.CreatedOn = date;
                tbl.Id = entity.Id;
                tbl.StatusId = (int)MasterEntityStatus.New;

                _ctx.TblPurchase.AddObject(tbl);
            }
            tbl.UpdatedOn = date;
            tbl.DocumentRef = entity.PurchaseOrderRef;
            tbl.FsrId = entity.FsrtId;
            tbl.PopId = entity.PopId;
            tbl.ClientId = entity.ClientId;
            foreach(var item in entity.Items)
            {
                TblPurchaseItem pitem = new TblPurchaseItem
                                            {
                                                Id=item.Id,
                                                CreatedOn = date,
                                                UpdatedOn = date,
                                                ReasonId=item.ReasonId,
                                                ProductId=item.ProductId,
                                                Quantity=item.Quantity,
                                                StatusId=0,
                                                Price=item.Price,
                                                
                                            };
                if(item.Quantity>0)
                    isSale = true;

                tbl.TblPurchaseItem.Add(pitem);
            }
            TblPointOfPurchaseVist vist = new TblPointOfPurchaseVist()
                                              {
                                                  
                                                  IsSale=isSale,
                                                  StatusId=0,
                                                  VistDate=date,
                                                  UpdatedOn=date,
                                                  CreatedOn=date,

                                              };
            tbl.TblPointOfPurchaseVist.Add(vist);
            _ctx.SaveChanges();
            return tbl.Id;
        }

        public PurchaseOrder GetById(Guid id)
        {
            var tbl = _ctx.TblPurchase.FirstOrDefault(s => s.Id == id);
            if (tbl == null) return null;
            return Map(tbl);
        }

        private PurchaseOrder Map(TblPurchase tbl)
        {
            PurchaseOrder entity = new PurchaseOrder
                                       {
                                           ClientId=tbl.ClientId,
                                           FsrtId=tbl.FsrId,
                                           Id=tbl.Id,
                                           PopId=tbl.PopId,
                                           PurchaseOrderRef=tbl.DocumentRef,
                                           Status = (MasterEntityStatus)tbl.StatusId,
                                           CreatedOn = tbl.CreatedOn,
                                           UpdatedOn = tbl.UpdatedOn,
                                       };
            foreach(var item in tbl.TblPurchaseItem)
            {
                PurchaseOrderItem pitem = new PurchaseOrderItem
                {
                    CreatedOn = item.CreatedOn,
                    UpdatedOn = item.UpdatedOn,
                    ReasonId = item.ReasonId,
                    ProductId = item.ProductId,
                    Quantity = item.Quantity.Value,
                    Status = 0,
                    Price = item.Price,
                    Id=item.Id,
                    PurchaseId=item.PurchaseId,

                };
                entity.Items.Add(pitem);
            }
            return entity;
        }

        public List<PurchaseOrder> GetAll()
        {
            return _ctx.TblPurchase.ToList().Select(n => Map(n)).ToList();
        }

       


        protected override string _cacheKey
        {
            get { throw new NotImplementedException(); }
        }

        protected override string _cacheListKey
        {
            get { throw new NotImplementedException(); }
        }

        public void Create(Guid orderId, int popId,int clientId, int userId, int appId, DateTime dateCreated, DateTime dateSent)
        {
            TblPurchase tbl = _ctx.TblPurchase.FirstOrDefault(s => s.Id == orderId);

            if (tbl == null)
            {
                tbl = new TblPurchase();
                tbl.CreatedOn = dateCreated;
                tbl.Id = orderId;
                tbl.StatusId = (int)MasterEntityStatus.New;
                _ctx.TblPurchase.AddObject(tbl);
            }
            tbl.UpdatedOn = dateCreated;
            tbl.DocumentRef = orderId.ToString();
            tbl.FsrId = userId;
            tbl.PopId = popId;
            tbl.ClientId = clientId;
            TblPointOfPurchaseVist vist = new TblPointOfPurchaseVist()
            {

                IsSale = false,
                StatusId = 0,
                PurchaseId=orderId,
                VistDate = dateCreated,
                UpdatedOn = dateCreated,
                CreatedOn = dateCreated,

            };
            tbl.TblPointOfPurchaseVist.Add(vist);
            _ctx.SaveChanges();
        }

        public void AddLineItem(Guid orderId, Guid lineItemId, int quantity, int productId, int reasonId,DateTime datecreated)
        {
            //TblPurchase tbl = _ctx.TblPurchase.FirstOrDefault(s => s.Id == orderId);
            TblPointOfPurchaseVist vist = _ctx.TblPointOfPurchaseVist.FirstOrDefault(s => s.PurchaseId == orderId);
            if ( vist!=null)
            {
                var product = _ctx.TblProduct.FirstOrDefault(p => p.Id == productId);
                TblPurchaseItem pitem = _ctx.TblPurchaseItem.FirstOrDefault(p => p.Id == lineItemId);
                if(pitem==null)
                {
                    pitem = new TblPurchaseItem
                                {
                                    Id = lineItemId,
                                    CreatedOn = datecreated,
                                    UpdatedOn = datecreated,
                                };
                    pitem.StatusId = 0;
                    _ctx.TblPurchaseItem.AddObject(pitem);
                }
               
                pitem.ReasonId = reasonId;
                pitem.ProductId = productId;
                pitem.Quantity = quantity;
                pitem.Price = product != null ? product.Price : 0;
                pitem.PurchaseId = orderId;
                if (quantity > 0)
                    vist.IsSale = true;
                //tbl.TblPurchaseItem.Add(pitem);
                
            }
            _ctx.SaveChanges();
        }

        public void Confirm(Guid orderId)
        {
            TblPurchase tbl = _ctx.TblPurchase.FirstOrDefault(s => s.Id == orderId);
            if (tbl != null)
            {
                tbl.StatusId = (int)MasterEntityStatus.Confirm;
            }
            _ctx.SaveChanges();
        }
    }
}
